<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {Loading, Refresh} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import {adminAddProductType, adminDeleteProductType, adminGetProductTypeList} from "@/router/api";

const formRef = ref<FormInstance>();
const form = reactive({id: '', name: ''});
const rules = ref({
  name: [
    {required: true, message: '请输入商品类型名称', trigger: 'blur'},
    {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'},
  ]
})
const dialogVisible = ref(false);
const tableData = ref<Array<{
  id: string;
  name: string;
  number: number;
}>>([]);
const loading = ref(false)
const isRefreshing = ref(false);

// 模拟刷新动画
const handleRefresh = () => {
  getProductTypeLists();
  isRefreshing.value = true;
  loading.value = true;
  setTimeout(() => {
    isRefreshing.value = false;
    loading.value = false;
  }, 1000);
};
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
const mapData = (data: Array<any>) => {
  return data.map((item) => ({
    id: item.id,
    name: item.name,
    number: item.number,
  }));
};
// 关闭弹窗
const handleClose = () => {
  formRef.value?.resetFields();
  form.name = '';
  dialogVisible.value = false;
};
//获取商品类型列表
const getProductTypeLists = async () => {
  try {
    const response = await adminGetProductTypeList();
    if (Array.isArray(response)) {
      tableData.value = mapData(response);
    }
  } catch (error) {
    showMessage('error', '获取商品类型列表失败');
  }
}
// 删除商品类型
const handleDelete = (row: any) => {
  ElMessageBox({
    title: '删除用户',
    message: '你确定要删除该商品类型？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    const response: any = await adminDeleteProductType(row.id);
    if (response > 0) {
      showMessage('warning', '无法删除，请先删除该商品类型下所有商品');
    } else {
      showMessage('success', '删除成功');
    }
    await getProductTypeLists();
  }).catch(() => {
    showMessage('info', '已取消删除');
  });
};
const handleAdd = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        //添加商品类型逻辑
        await adminAddProductType(form.name);
        await getProductTypeLists();
        dialogVisible.value = false;
        formEl.resetFields();
        form.name = '';
        showMessage('success', '添加成功')
      } catch (e) {
        showMessage('error', '添加失败');
      }
    }
  })
}
onMounted(() => {
  getProductTypeLists();
})
</script>

<template>
  <div class="admin-container">
    <el-button @click="dialogVisible = true" type="warning" plain class="buttons">添加商品类型
    </el-button>
    <div class="refresh-container">
      <el-icon v-if="isRefreshing" class="loading-icon">
        <Loading/>
      </el-icon>
      <el-icon v-else class="refresh-icon">
        <Refresh @click="handleRefresh"/>
      </el-icon>
    </div>
  </div>
  <el-table :data="tableData" border style="width: 100%" highlight-current-row v-loading="loading">
    <el-table-column prop="name" label="商品类型" show-overflow-tooltip align="center"/>
    <el-table-column prop="number" label="其下商品数量" show-overflow-tooltip align="center"/>

    <el-table-column fixed="right" label="操作" show-overflow-tooltip align="center" width="200">
      <template #default="scope">
        <el-button size="small" @click="handleDelete(scope.row)" type="danger">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="dialogVisible" title="添加商品类型" width="500" center draggable>
    <el-form ref="formRef" :model="form"
             :rules="rules"
             status-icon
             scroll-to-error
             size="default">
      <el-form-item label="商品类型名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品类型名称"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleAdd(formRef)">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.admin-container {
  width: 100%;
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.refresh-container {
  margin-top: 4px;
  margin-left: 20px;
}

.loading-icon {
  color: #707581;
  font-size: 26px;
  animation: spin 1s infinite linear;
}

.refresh-icon {
  color: #707581;
  cursor: pointer;
  font-size: 26px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
